package com.nuoniu.sibanyun.config;

import com.nuoniu.sibanyun.filter.JWTAuthenticationFilter;
import com.nuoniu.sibanyun.filter.JWTAuthorizationFilter;
import com.nuoniu.sibanyun.interceptor.handler.CustomAccessDeineHandler;
import com.nuoniu.sibanyun.interceptor.CustomAuthenticationEntryPoint;
import com.nuoniu.sibanyun.interceptor.handler.MyAuthenticationFailureHandler;
import com.nuoniu.sibanyun.interceptor.handler.MyLogoutHandler;
import com.nuoniu.sibanyun.interceptor.handler.MyLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private MyLogoutHandler myLogoutHandler;

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 由于使用的是JWT，我们这里不需要csrf
                .csrf().disable()
                // cors():允许跨域访问
                .cors()

//                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/auth/**").permitAll()
                .antMatchers("/verifyCode/**").permitAll()
                //.antMatchers("/webSocket/**").permitAll()
               // .antMatchers("/uploadFile/**").permitAll()
//                .antMatchers("/admin/**").hasRole("ADMIN")
//                .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
//                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()// //对preflight放行,非简单请求 进行的OPTIONS 请求
                // swagger start
                .antMatchers("/in/inventory/dAllOrder").permitAll()
                .antMatchers("/editorUpload").permitAll()
                .antMatchers("/weXin/pay").permitAll()
                .antMatchers("/crm/customer/importTemplate").permitAll()
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger*/**").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/**").permitAll()
                .antMatchers("/configuration/ui").permitAll()
                .antMatchers("/configuration/security").permitAll()
                .antMatchers("/crm/invitationForm/getDetail").permitAll()
                .antMatchers("/crm/invitationForm/save").permitAll()
                .antMatchers("/crm/invitationForm/sendSms").permitAll()
                .antMatchers("/crm/callTaskRecord/addCallBackInfo").permitAll()
                .antMatchers("/crm/callTaskRecord/callBackRecordFromXiangYun").permitAll()
                .antMatchers("/crm/callTaskRecord/callBackRecordFromRongYing").permitAll()
                .antMatchers("/crm/callTaskRecord/listenerStateFromRongYing").permitAll()
                .antMatchers("/crm/callTaskRecord/uploadAudio").permitAll()
                .antMatchers("/erp/voucherDesign/voucherDynamicById").permitAll()
                //.antMatchers("/vendor/exportData").permitAll()
//                .antMatchers("/uReport/**").anonymous()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                // 不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
                .accessDeniedHandler(new CustomAccessDeineHandler())
//                .and().httpBasic().disable()
                .and()
                .logout()
                .addLogoutHandler(myLogoutHandler)
                .logoutSuccessHandler(new MyLogoutSuccessHandler())
                ;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //allow Swagger URL to be accessed without authentication
        web.ignoring().antMatchers("/v2/api-docs",//swagger api json
                "/swagger-resources/configuration/ui",//用来获取支持的动作
                "/swagger-resources",//用来获取api-docs的URI
                "/swagger-resources/configuration/security",//安全选项
                "/swagger-ui.html");
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

    @Bean
    public AuthenticationFailureHandler customAuthenticationFailureHandler() {
        return new MyAuthenticationFailureHandler();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setHideUserNotFoundExceptions(false);
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(bCryptPasswordEncoder);
        return provider;
    }
}
